package icu.lookyousmileface.volatilecode;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author starrysky
 * @title: AtomicUse
 * @projectName Juc_Pro
 * @description: 原子类使用
 * @date 2021/1/3011:51 上午
 */
public class AtomicUse {

    private volatile static AtomicInteger number = new AtomicInteger();

    public static void add(){
        number.getAndIncrement();
    }

    public static void main(String[] args) {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                Runtime.getRuntime().availableProcessors(),
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()

        );

        try {
            for (int i = 1; i <= 20; i++) {
                threadPoolExecutor.execute(()->{
                    for (int j = 1; j <= 1000; j++) {
                        add();
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
        /**
         * 让出主线程的CPU时间片，让其他线程使用
         */
        while (Thread.activeCount()>2){
            System.out.println(Thread.currentThread().getName());
            Thread.yield();
        }
        System.out.println("result:"+number);
    }
}
